<template>
  <div class="about-master-container">
    <base-breadcrumb
      :breadcrumb="!isAudit"
      :state="state"
    >
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="合同种类"
                    prop="typeId"
                  >
                    <a-select
                      v-model="formData.typeId"
                      :disabled="state === 3 || formData.id !== null"
                    >
                      <a-select-option
                        v-for="item in speciesArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col
                  v-if="isContract"
                  span="8"
                >
                  <a-form-model-item
                    label="物资招标定标编号"
                    prop="countersignCode"
                  >
                    <a-input-search
                      v-model="formData.tenderCode"
                      placeholder="请选择"
                      :disabled="state === 3 || formData.id !== null"
                      @search="onSearch"
                      @click="onSearch"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col
                  v-else
                  span="8"
                >
                  <a-form-model-item
                    label="采购合同编号"
                    prop="origContractCode"
                  >
                    <a-input-search
                      v-model="formData.origContractCode"
                      placeholder="请选择"
                      :disabled="state === 3 || formData.id !== null"
                      @search="$refs.ContractReview.open()"
                      @click="$refs.ContractReview.open()"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="工程名称">
                    <a-select
                      v-model="formData.constructionTypeId"
                      disabled
                    >
                      <a-select-option
                        v-for="item in getProgrammeArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="物资合同评审编码">
                    <BaseInput
                      v-model="formData.contractCode"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="供应商名称"
                    prop="supplier"
                  >
                    <BSelect
                      v-if="isContract"
                      v-model="formData.supplierId"
                      @selectChange="getSupplier"
                      :form="formData"
                      :disabled="state === 3"
                      placeholder="请选择"
                      keyValue="tenderId"
                      :init="false"
                      :request="e=>supplierListUrl({id : formData.tenderId})"
                    />

                    <a-input-search
                      v-else
                      v-model="formData.supplier"
                      placeholder="请选择"
                      :disabled="disabled"
                      @search="searchSupplier"
                      @click="searchSupplier"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="合同编号"
                    prop="code"
                  >
                    <BaseInput
                      v-model="formData.code"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="供应商编码">
                    <BaseInput
                      v-model="formData.supplierCode"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="合同类别"
                    prop="contractTypeId"
                  >
                    <a-select
                      v-model="formData.contractTypeId"
                      :disabled="disabled"
                      @change="typeLabelChange"
                    >
                      <a-select-option
                        v-for="item in typeArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col
                  span="8"
                  v-if="formData.contractTypeCode !=='140001' && formData.contractTypeCode !=='140006'"
                >
                  <a-form-model-item
                    label="材料类别"
                    prop="materialClassId"
                  >
                    <BSelect
                      :form="formData"
                      keyValue="contractTypeCode"
                      v-model="formData.materialClassId"
                      :request="typeLabel(36)"
                      :disabled="disabled2"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="合同文本"
                    prop="textId"
                  >
                    <a-select
                      v-model="formData.textId"
                      :disabled="disabled"
                    >
                      <a-select-option
                        v-for="item in textArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="前期招标资料"
                    prop="preBidFiles"
                  >
                    <a-select
                      v-model="formData.preBidFiles"
                      :disabled="disabled"
                    >
                      <a-select-option :value="1">具备</a-select-option>
                      <a-select-option :value="0">不具备</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="对方签约授权委托"
                    prop="delegation"
                  >
                    <a-select
                      v-model="formData.delegation"
                      :disabled="disabled"
                    >
                      <a-select-option :value="1">具备</a-select-option>
                      <a-select-option :value="0">不具备</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="合同价款(税前)">
                    <BaseInput
                      v-model="formData.contractPrice"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="合同名称"
                    prop="name"
                  >
                    <BaseInput
                      v-model="formData.name"
                      :disabled="disabled"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="合同份数"
                    prop="size"
                  >
                    <BaseInput
                      v-model="formData.size"
                      type="number"
                      :disabled="disabled"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="评审文件上传"
                    prop="fileInfo"
                  >
                    <l-table
                      :count="1"
                      :multiple="false"
                      :is-close="state!==3"
                      :upload-arrys.sync="formData.fileInfo"
                      business-code="MM13"
                      @fileArrysData="fileArrysData"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col>
                  <a-form-model-item
                    label="评审内容"
                    prop="reviewContent"
                  >
                    <editor
                      v-model="formData.reviewContent"
                      :max-length="100000"
                      :is-clear="true"
                      :disabled="state === 3"
                      @change="commentsVal"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="tempSave()"
              >保存草稿</a-button>
              <a-button
                type="primary"
                @click="tempSave(true)"
              >下一步</a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="物资明细">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <materials
              ref="materials"
              :state="state"
              :row="formData"
              :is-contract="isContract"
              @getTotal="getTotal"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >上一步</a-button>
              <a-button
                type="primary"
                :disabled="!formData"
                @click="next"
              >下一步</a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="评审意见表">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <opinion
              :id="formData.id "
              ref="opinion"
              :state="state"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >上一步</a-button>
              <a-button
                type="primary"
                :disabled="!formData"
                @click="next"
              >下一步</a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[3]||isAudit"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="formData.id"
              business-code="MM09"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >上一步</a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div
        v-if="!isAudit"
        class="pub-header-btn page-btn-right-top"
      >
        <a-button
          v-if="state !== 3"
          :loading="loading"
          type="primary"
          @click="submit"
        >提交</a-button>
        <BasePrintButton
          v-if="formData.id && state == 3"
          :before-print-fn="beforePrintFn"
          style="display: inline-block"
        />
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >关闭</a-button>
      </div>
      <div
        v-else
        class="pub-header-btn page-btn-right-top"
      >
        <a-button
          v-checkVisibleInDetail
          @click="handleClose"
        >关闭</a-button>
      </div>
    </base-breadcrumb>
    <supplier-list
      ref="supplierList"
      :other-url="supplierListUrl"
      :other-data="{id : formData.tenderId}"
      @createList="getSupplier"
    />
    <!--    <sign-->
    <!--      ref="sign"-->
    <!--      @getSign="getSign"-->
    <!--    />-->
    <tender
      ref="sign"
      @getSign="getSign"
    />
    <ContractReview
      :other-params="{popover :1}"
      ref="ContractReview"
      @ok="getContractReview"
    />
  </div>
</template>
<script>
import { contractReviewAdd, contractReviewEdit, audit, addFile, fileDel, fileListReview, contractReviewDetail, findSupplierById, print, findSupplierById2 } from '@/api/material/contract/review'
import { selectOption } from '@/api/material/goods/goods'
import sign from '../components/sign/sign'
import tender from '../components/tender'
import materials from '../components/materials/materials'
import opinion from '../components/opinion/opinion'
import editor from '@/components/Editor/editor'
import ContractReview from '@/views/materials/components/dialog/ContractReview'
import { materialApiUrl } from '@/api/config'

export default {
  name: 'a' + Date.now(),
  components: {
    sign,
    materials,
    opinion,
    editor,
    ContractReview,
    tender
  },
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      beforePrintFn: async () => {
        let res = await print({ id: this.formData.id })
        return res.data.content
      },
      supplierListUrl: findSupplierById2,
      activeKey: [true, false, false, false, false, false, false],
      stepVal: 0,
      state: Number(this.$route.query.state),
      isSubmit: false,
      loading: false,
      row: this.$route.query.row,
      formData: {
        id: null,
        createTime: this.getNowTime(),
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        typeId: null,
        countersignCode: null,
        constructionTypeId: null,
        contractCode: '',
        supplier: '',
        tenderId: '',
        supplierCode: '',
        contractTypeId: null,
        contractTypeCode: null,
        materialClassId: '',
        materialClassName: '',
        textId: null,
        contractPrice: '',
        reviewContent: '',
        supplierId: undefined,
        countersignId: null,
        preBidFiles: 1,
        delegation: 0,
        code: '',
        commonFileId: null,
        fileInfo: [],
        name: '',
        size: ''
      },
      rules: {
        materialClassId: { required: true, message: '请选择材料类别', trigger: 'change' },
        typeId: { required: true, message: '请输入编号', trigger: 'change' },
        size: { required: true, message: '请输入合同份数', trigger: 'change' },
        name: { required: true, message: '请输入合同名称', trigger: 'change' },
        countersignCode: { required: true, message: '请选择物资招标评审会签编码', trigger: 'change' },
        supplier: { required: true, message: '请选择供应商名称', trigger: 'change' },
        code: { required: true, message: '请输入合同编号', trigger: 'blur' },
        contractTypeId: { required: true, message: '请选择合同类别', trigger: 'change' },
        textId: { required: true, message: '请选择合同文本', trigger: 'change' },
        preBidFiles: { required: true, message: '请选择前期招标资料', trigger: 'change' },
        delegation: { required: true, message: '请选择对方签约授权委托', trigger: 'change' },
        fileInfo: { required: true, message: '请选择评审文件', trigger: 'change' }
      },
      typeArr: [],
      speciesArr: [],
      textArr: [],
      isNext: false,
      init: false,
      addFile: materialApiUrl + '/materials/contract_review/addFile',
      fileDel: materialApiUrl + '/materials/contract_review/deleteFile',
      fileList: fileListReview(),
      getProgrammeArr: [],
      typeLabel: (type) => {
        return async () => {
          let res = await selectOption({ type })
          if (res.code === this.SUCCESS_CODE) {
            if (res.data instanceof Array) {
              return { code: 200, data: res.data.filter((v) => v.code === this.formData.contractTypeCode) }
            }
            return { code: 200, data: [] }
          }
          return { code: 500 }
        }
      }
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    },
    'formData.typeId'() {
      if (!this.init) return
      this.formData.supplierId = ''
      this.formData.supplier = ''
      this.formData.supplierCode = ''
      this.formData.contractCode = ''
      this.formData.constructionTypeId = ''
      this.formData.code = ''
      this.formData.contractTypeId = ''
      this.formData.textId = ''
      this.formData.preBidFiles = undefined
      this.formData.delegation = undefined
      this.formData.contractPrice = ''
      this.formData.name = ''
      this.formData.size = ''
      this.formData.reviewContent = ''
      this.formData.origContractCode = ''
      this.formData.tenderCode = ''
      this.formData.fileInfo = []
    }
  },
  computed: {
    disabled() {
      if (this.state === 3) return true
      else return !this.isContract
    },
    disabled2() {
      if (this.state === 3) return true
      if (this.isContract) {
        return false
      } else {
        return !!this.formData.materialClassId
      }
    },
    isContract() {
      let res = this.speciesArr.find((v) => v.id === this.formData.typeId)
      if (res) {
        return res.name === '采购合同'
      }
      return true
    }
  },
  mounted: async function () {
    this.loading = true
    await this.getType()
    await this.getSpecies()
    await this.getText()
    await this.getProgramme()
    if (this.$route.query.id) {
      this.formData.id = this.$route.query.id
      await this.getData()
      this.isSubmit = true
      this.init = true
      if (this.state === 3) {
        this.activeKey = [true, true, true, true, false, false, false]
      }
    } else {
      this.init = true
    }
    this.loading = false
  },
  methods: {
    typeLabelChange(e) {
      this.formData.materialClassName = this.formData.materialClassId = ''
      let res = this.typeArr.find((v) => v.id === e)
      if (res) {
        this.formData.contractTypeCode = res.code
      }
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    },
    getContractReview(row) {
      console.log(row)

      this.formData.origContractId = row.materialContractLocalId
      this.formData.origContractCode = row.code
      this.formData.constructionTypeId = row.constructionTypeId
      this.formData.contractCode = row.contractCode
      this.formData.supplier = row.supplier
      this.formData.supplierCode = row.supplierCode
      this.formData.textId = row.textId
      this.formData.supplierId = row.supplierId
      this.formData.contractTypeId = row.contractTypeId
      let res = this.typeArr.find((v) => v.id === row.contractTypeId)
      if (res) {
        this.formData.contractTypeCode = res.code
      }
      this.formData.materialClassId = row.materialClassId
      this.formData.materialClassName = row.materialClassName
      this.formData.preBidFiles = row.preBidFiles ? 1 : 0
      this.formData.delegation = row.delegation ? 1 : 0
      this.formData.contractPrice = row.contractPrice
      this.formData.fileInfo = (row.fileInfo && [row.fileInfo]) || []
      this.formData.reviewContent = row.reviewContent
      this.formData.name = row.name
      this.formData.size = row.size
    },
    async getData() {
      this.loading = true
      let res = await contractReviewDetail({ id: this.formData.id })
      if (res.code === 200) {
        this.formData = { ...this.formData, ...res.data }
        this.formData.fileInfo = (res.data.fileInfo && [res.data.fileInfo]) || []
        this.formData.typeId = String(res.data.typeId)
        this.formData.preBidFiles = this.formData.preBidFiles ? 1 : 0
        this.formData.delegation = this.formData.delegation ? 1 : 0
        let res2 = this.typeArr.find((v) => v.id === this.formData.contractTypeId)
        if (res2) {
          this.formData.contractTypeCode = res2.code
        }
      } else {
        this.$message.warning('获取详情失败')
      }
      this.loading = false
    },
    async tempSave(isNext) {
      if (this.state === 3) return this.next()
      this.$refs.ruleForm.validate(async (valid, object) => {
        if (valid) {
          let { fileInfo } = this.formData
          let params = {
            ...this.formData,
            fileInfo: (fileInfo && fileInfo.length > 0 && fileInfo[0]) || void 0
          }
          this.loading = true
          if (this.formData.id) {
            let res = await contractReviewEdit(params)
            if (res.code === 200) {
              this.$message.success('暂存成功')
              this.isSubmit = true
              if (isNext) {
                this.next()
              }
            }
          } else {
            let res = await contractReviewAdd(params)
            if (res.code === 200) {
              this.$message.success('暂存成功')
              this.isSubmit = true
              this.formData.id = res.data.id
              await this.getData()
              if (isNext) {
                this.next()
              }
            }
          }
          this.loading = false
        } else {
            this.$message.warning("请填写完所有必填项信息")
          this.$noticeWarning('请填写完整')
        }
      })
    },
    stepChange: function (val) {
      if (!this.isSubmit) {
        this.$message.warning('切换步骤前请先填写基本信息')
        this.stepVal = 0
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    previous: function () {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },
    next: function (val) {
      this.isNext = true
      this.stepVal++
    },
    commentsVal: function (val) {
      this.formData.reviewContent = val
    },
    async fileArrysData(list) {
      this.formData.fileInfo = [...list]
      this.$refs.ruleForm.validateField('fileInfo')
    },
    getTotal: function (total) {
      this.formData.contractPrice = total.sumTotal
    },
    async getSign(selectRow) {
      this.formData.countersignCode = selectRow.tenderCountersignCode
      this.formData.countersignId = selectRow.tenderReviewCountersignId
      this.formData.constructionTypeId = selectRow.wbsId
      this.formData.tenderId = selectRow.id
      this.formData.tenderCode = selectRow.selectionCode
    },
    searchSupplier: function () {
      if (!this.formData.countersignCode) {
        return this.$noticeWarning('请选择物资招标评审会签编码！')
      }
      this.$refs.supplierList.open()
    },
    getSupplier: function (selectRow) {
      this.formData.supplier = selectRow.name
      this.formData.supplierCode = selectRow.code
      this.formData.supplierId = selectRow.id
    },
    onSearch: function (val) {
      this.$refs.sign.open()
    },
    async getProgramme() {
      let res = await selectOption({ type: 18 })
      if (res.code === 200) {
        this.getProgrammeArr = res.data
      }
    },
    async getType() {
      let res = await selectOption({ type: 14 })
      if (res.code === 200) {
        this.typeArr = res.data
        let res2 = this.typeArr.find((v) => v.name === '物资采购')
        if (res2) {
          this.formData.contractTypeId = res2.id
          this.formData.contractTypeCode = res2.code
        }
      }
    },
    async getSpecies() {
      let res = await selectOption({ type: 8 })
      if (res.code === 200) {
        this.speciesArr = res.data
        this.formData.typeId = this.speciesArr[0].id
      }
    },
    async getText() {
      let res = await selectOption({ type: 9 })
      if (res.code === 200) {
        this.textArr = res.data
        this.formData.textId = this.textArr[0].id
      }
    },

    async submit() {
      // this.save('approve');
      if (this.isSubmit) {
        this.loading = true
        let res = await audit({ baseId: this.formData.id, auditStatus: this.formData.auditStatus })
        if (res.code === 200) {
          this.$message.success('提交成功')
          this.$router.push({ path: '/material/contract/review' })
        }
        this.loading = false
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    }
  }
}
</script>
